#include <stdlib.h>
#include "includes/mybitmap.h"

mybitmap *mybitmap_crate(int byte_size) {
    mybitmap *b = malloc(sizeof(mybitmap));
    uint8_t *d = calloc(byte_size, 1);
    b->data = d;
    b->size = byte_size * 8;
    b->used = 0;
    return b;
}

int mybitmap_get(mybitmap *b, int off) {
    int idx = off / 8;
    int byte_off = off % 8;
    return b->data[idx] & (1 << byte_off);
}

void mybitmap_set(mybitmap *b, int off) {
    if(mybitmap_get(b, off)) return;
    int idx = off / 8;
    int byte_off = off % 8;
    b->data[idx] |= (1 << byte_off);
    b->used++;
}

void mybitmap_clear(mybitmap *b, int off) {
    if(!mybitmap_get(b, off)) return;
    int idx = off / 8;
    int byte_off = off % 8;
    b->data[idx] &= ~(1 << byte_off);
    b->used--;
}

int mybitmap_allocate(mybitmap *b) {
    for (int i = 0; i < b->size/8; i++)
    {
        uint8_t d = b->data[i];
        if(d != 0xff) {
            for (int j = 0; j < 8; j++)
            {
                if(!(d & (1 << j))) {
                    int off = i * 8 + j;
                    mybitmap_set(b, off);
                    return off;
                }
            }
            
        }
    }
    
}
